import React, { PropTypes, Component } from 'react';
import { Link } from 'react-router'
import style from './WorkloadM.css';
import { getAdminInfo, getAuthShop, myAjaxJson, ROOTURL } from './../publicAPI/publicAPI';




export default React.createClass({
	getInitialState: function() {
		let _this = this;

		//获取当前登录信息，用于记录订单创建人
		getAdminInfo(function(data) {
			console.log(data);
			this.setState({
				userid: data.id,
				userName: data.uname,
			});
		}.bind(_this), function(error) {})

	    return {
	    	shopsForAdm: [],
	    	baber: [],
	    	shopsData: [],
	    	assistant: [],
	    	serTypesForShop: [],
		};
	},

	componentWillMount: function() {
		let _this = this;


		//获取所有店铺名
		getAuthShop(null, function(data) {
			console.log(data);
			var shopsForAdm = [];
			let shopsId = {};
			data.forEach((shopMes) => {
				shopsForAdm.push(shopMes.dname);
				shopsId[shopMes.dname] = shopMes.id;
			}); 
			console.log(shopsForAdm);
			this.setState({
				shopsData: data,
				shopsForAdm: shopsForAdm,
				shopsId: shopsId,

			});
		}.bind(_this));
		
	},
	componentDidMount: function() {
		let _this = this;
		
			
	},
	//商店选择后
	shopSelect: function() {
		let _this = this;
		let shopSelect = this.refs.shopSelect.value;
		if(shopSelect == '请选择店铺名称') return;

		//列出所属理发师和助理
		fetch(ROOTURL +'servant/profile/search.api', { 
            method : 'POST',
            mode: 'cors',
            body: JSON.stringify({})
        })
        .then(res=>{
        	if(res.ok){
                res.json().then(function(data) {    	
                	console.log(data);
                	let assistant = [];
                	let servantsId = {};
		            let baber = data.filter(function(servantData) {
		            	servantsId[servantData.meta.name] = servantData.id;
		            	if(!servantData.dd&&(servantData.meta.shop==shopSelect)) {
		            		if(servantData.meta.isAssistant) {
		            			assistant.push(servantData.userid);
		            		}
		            		else {
		            			return true
		            		}
		            	} else return false 
		            });
		            console.log(assistant);
		            console.log(baber);
		            this.setState({
		            	assistant: assistant,
		            	baber: baber,
		            	servantsId: servantsId,
		            });
            	}.bind(_this))
            }
        }) 
        .catch(function (error) { 
            console.log('Request failed', error); 
        });

        //列出该门店的服务类型
        let shopName = this.state.shopsData.filter((shop, idx) => {
        	if(shop.dname == shopSelect) {
        		return true
        	} else { return false }
        });
        console.log(shopName);
 		fetch(ROOTURL + '/serv/shop/search.api', {
            method : 'POST',
            //mode: 'cors',
            body: JSON.stringify({
            	id: shopName.id,
            	name: shopName.dname,
            })
        }).then((res)=>{
            if(res.ok){
                res.json().then((data)=>{
                    console.log(data);
                    let serTypesId = {};
                    let serTypesForShop = data.filter((type, idx)=> {
                    	serTypesId[type.dname] = type.id;
                    	return !type.dd
                    });
                    console.log(serTypesForShop);
                    this.setState({
                    	serTypesForShop: serTypesForShop,
                    	serTypesId: serTypesId,
                    });
                })
            }
        })
		.catch(function (error) { 
            console.log('Request failed', error); 
        });
	},

	matchPrice: function() {
		let price = this.refs.price.value;
		if((typeof price) != 'number') {
			console.log('格式错误');
		}
	},

	handleSubmit: function() {
		let _this = this;
		//判断时间
		let a=0; 
		if(/^20\d{2}$/.test(this.refs.crYear.value)) {
			console.log('年格式正确');
			if(/^[1-9]{1}$/.test(this.refs.crMonth.value)||/^1{1}[0-2]{1}$/.test(this.refs.crMonth.value)) {
				console.log('月格式正确');
				if(/^0?[1-9]$|^1[1-9]$|^2[1-9]$|^3[0-1]$/.test(this.refs.crDay.value)) {
					console.log('年月日格式正确');
					if(/^[0-1]?[0-9]$|^2[0-4]$/.test(this.refs.crHour.value)) {
						console.log('小时格式正确');
						if(/^[0-5]?[0-9]$/.test(this.refs.crMinute.value)) {
							console.log('分钟格式正确');
							a=1;
						}
					}
				}
			}
		}
		if(!a) {
			alert('输入时间有误！');
			return
		}
		
		let nowTime = new Date();
		nowTime.setFullYear(this.refs.crYear.value, this.refs.crMonth.value-1, this.refs.crDay.value);
		let crTime = nowTime.setHours(this.refs.crHour.value, this.refs.crMinute.value);
		//console.log(crTime.toLocaleString());
		//判断数据是否为空，是否格式正确
		if(!this.refs.baberName.value||!this.refs.shopSelect.value||!this.refs.serType.value) {
			alert('门店、理发师、服务项目不能为空');
			return 
		}

		if(!parseFloat(this.refs.grossPay.value)||!parseFloat(this.refs.netPay.value)) {
			alert('价格错误，请检查格式是否正确！');
			return 
		}
		//alert('jixu');
		//发送数据至服务器
		let param = {};
		param.creator = this.state.userid;
		//订单创建时间
        param.tmCreate = nowTime.getTime();
		param.dd = false;
		//param.customer = this.refs.customer.value;
		param.servant = this.state.servantsId[this.refs.baberName.value];
        param.shop = this.state.shopsId[this.refs.shopSelect.value];
        param.servType= this.state.serTypesId[this.refs.serType.value];
        //标准价格
        param.grossPay = parseFloat(this.refs.grossPay.value);
        //实际支付价格
        param.netPay = parseFloat(this.refs.netPay.value);
        //服务开始时间
        param.tmServe = crTime;
        param.meta =  {
            //是否是顾客指定理发师
            isChoosed: this.refs.isChoosed.checked,
            //支付方式
            payment: this.refs.payment.value,
            //备注
            message: this.refs.message.value,
            //订单创建人
            creatorName: this.state.userName,
            //服务类型
            serType: this.refs.serType.value,
            //理发师助理
            assistant: this.refs.assistant.value||'无',
            //判断是否复核过
            isChecked: false,
            //是否通过审核
            permission: false,
            //审核人
            whoChecked: '未审核',
            //判断是否主订单
            //attaching: null,
        }
        //没写的项目
        //param.stPayment = 16;//支付状态
        //param.tmReserve = crTime;//预计接受服务时刻
        console.log(param);

		myAjaxJson(ROOTURL + 'contract/offline/instance.api', 'POST', param, function(data3) {
			console.log(data3);
			console.log(_this.refs.assistant.value);
			//判断并录入理发师助理的订单,通过attaching标记
			if(_this.refs.assistant.value != '无') {
				//修改param
				param.attaching = data3.id;
				param.servant = _this.state.servantsId[_this.refs.assistant.value];
				console.log(param);
				//创建理发师助理订单
				myAjaxJson(ROOTURL + 'contract/offline/instance.api', 'POST', param, function(data4) {
					console.log(data4);
					console.log('创建从订单(助理)成功');
					alert('录入成功');
					window.location.href = '/SalaryM/WorkloadTable';
				}, function(error) {});
			} else {
				alert('录入成功');
				window.location.href = '/SalaryM/WorkloadTable';
			}
							
		}, function(error3) {
			alert('录入失败');
		});
		
	},

	handleKeyPress: function(e) {
	    if(e.which == 13) {
	        this.handleSubmit();
	    }
	},

	render: function() {
		let time = new Date();
		return (
			<div className={style['workloadM_wrapper']}>
				<div  className={style['workloadM_form']}>
			    	<p>
			    		<label>店铺名称：</label>
				    	<select ref="shopSelect" onChange={this.shopSelect}>
				    		<option value="请选择店铺名称">请选择店铺名称</option>
				    		{
			                    this.state.shopsForAdm.map((shop, idx) => {
			                    	return (
		                                <option value={shop} key={idx+1}>{shop}</option>
			                    	);
			                    })
				    		}
				    	</select>
			    	</p>
			    	<p>
			    		<label>理发师姓名：</label>
			    		<select ref="baberName">
							{
								this.state.baber.map((value, idx) => {
									return (
		                                <option value={value.meta.name} key={idx}>{value.meta.name}</option>
			                    	);
								})
							}
			    		</select>
			    	</p>

						<p>
							<label>服务项目：</label>
							<select ref="serType">
								{
									this.state.serTypesForShop.map((type, idx) => {
										return (
											<option value={type.dname} key={idx}>{type.dname}</option>
										);
									})
								}
							</select>
						</p>

						<p>
							<label>标准价格：</label><input type="text" style={{width: '50px'}} ref="grossPay" />&nbsp;&nbsp;&nbsp;
							<label>实收价格：</label><input type="text" style={{width: '50px'}} ref="netPay" />
						</p>
						
						<p>
							<label>收款渠道：</label>
							<select ref="payment">
								<option value="拉卡拉">拉卡拉</option>
								<option value="大众点评">大众点评</option>
								<option value="百度糯米">百度糯米</option>
								<option value="充值机">充值机</option>
							</select>
						</p>
						<p>
							<label>助理：</label>
							<select ref="assistant">
								<option>无</option>
								{
									this.state.assistant.map((value, idx) => {
										return (
											<option value={value} key={idx}>{value}</option>
										);
									})
								}
							</select>
						</p>
						<p>
							<label style={{width: '200px'}}>顾客是否指定该理发师：</label>
							<input type="checkbox" ref="isChoosed" />
						</p>
						<p><label style={{width: '115px'}}>服务开始时间：</label>
							<input type="text" placeholder="20xx" style={{width: '50px'}} ref="crYear" />年
							<input type="text" placeholder="0~12" style={{width: '50px'}} ref="crMonth" />月
							<input type="text" placeholder="0~31" style={{width: '50px'}} ref="crDay" />日
							<input type="text" placeholder="0~24" style={{width: '50px'}} ref="crHour" />:
							<input type="text" placeholder="0~59" style={{width: '50px'}} ref="crMinute" />
						</p>
						<p><label>备注：</label><input type="text" ref="message" /></p>
				</div>	
		    	<div>
					<button className={style['workloadM_button']} onClick={this.handleSubmit}>保存</button>
					<Link to={`/SalaryM/WorkloadTable`}>
						<button className={style['workloadM_button']}>返回</button>
					</Link>	
				</div>
    		</div>
		);
		
	}
});
    
